<!--  commi-->
<template>
  <div class="commi">
    <div class="flex align-center" v-if="!calcDisabled">
      <span class="tit_span nowarp" style="font-size:14px">分润方案：</span>
      <el-select
        v-model="valueId"
        placeholder="请选择"
        :disabled="calcDisabled"
      >
        <el-option
          v-for="item in options"
          :key="item.Id"
          :label="item.SpName"
          :value="item.Id"
        >
        </el-option>
      </el-select>
      <el-button
        v-if="alldisabled && options && options.length == 0"
        type="info"
        class="m-l-1"
        @click="toPath()"
        >新增</el-button
      >
    </div>
    <p class="m-r-1">
      <span>分润名称：</span>
      <span>{{ itemObj.SpName || "-" }}</span>
    </p>
    <div class="flex align-center" >
      <span class="tit_span nowarp" style="font-size:14px">补贴时间：</span>
              <el-input
                  type="number"
                  v-model="itemObj.SubsidyDate"
                  min="0"
                  @keyup.native="proving2($event)"
                  class="w300 "
                >
                  <template slot="append">天</template>
                </el-input>
    </div>

    <!-- <div class="flex align-center">
      <p class="m-r-1">
        <span class="">开始时间：</span>
        <span>{{ itemObj.StartTime || "-" }}</span>
      </p>
      <p class="m-r-1">
        <span class="">结束时间：</span>
        <span>{{ itemObj.EndTime || "-" }}</span>
      </p>
    </div> -->
    <div class="flex m-t-1">
      <span class="sp_span">备注：</span>
      <div>{{ itemObj.Remark || "-" }}</div>
    </div>
    <div class="auto-scroll m-t-1">
      <div
        class="flex m-t-1 align-center space-between ladder_item"
        v-for="(item, index) of list"
        :key="index"
      >
        <div class="ladder_name">{{ item.StairName || "-" }}</div>
        <div class="flex-1">
          <div
            class="flex align-center space-between ladder_cell"
            v-for="(cell, idx) of item.Settings"
            :key="idx"
          >
            <span>{{ cell.TargetName || "-" }}</span>
            <span>{{ cell.TargetNum || "-" }}</span>
            <div>
              <p
                class="flex align-center"
                v-for="lis of cell.Ratios"
                :key="lis.Id"
              >
                <span>{{ lis.ShareName }}：</span>
                <el-input
                  type="number"
                  v-model="lis.ShareRation"
                  placeholder="分润比例"
                  @keyup.native="proving2($event, '%')"
                  :disabled="alldisabled"
                >
                  <template slot="append">%</template>
                </el-input>
                <span class="m-l-1 nowrap px12">补贴：</span>
                <el-input
                  type="number"
                  v-model="lis.Subsidy"
                  placeholder="补贴比例"
                  min="0"
                  @keyup.native="proving2($event, '%')"
                  class="w100 none-padding"
                >
                  <template slot="append">%</template>
                </el-input>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-button
      type="primary"
      class="m-t-1"
      style="float: right"
      @click="SaveCorrsFun"
      >{{ "保存" }}</el-button
    >
  </div>
</template>

<script>
import { getShare, getShareDetail, saveShare } from '@/api/system/share-manage'
import { SaveCorrs, GetCorrList } from '@/api/system/user'

export default {
  //import引入的组件需要注入到对象中才能使用
  name: 'commi',
  components: {},
  data () {
    //这里存放数据
    return {
      valueId: "",
      itemObj: {},
      options: null,
      list: [],
      number: 0
    };
  },
  props: {
    alldisabled: {
      type: Boolean,
      default: false
    },
    RoleId: {
      type: String,
      default: ''
    },
    IdentityId: {
      type: String,
      default: ''
    },
    IsSystem: {
      type: Number,
      default: 2
    }

  },
  //监听属性 类似于data概念
  computed: {
    calcDisabled () {
      if (this.IsSystem == 3 || this.IsSystem == 4) {
        return false
      } else {
        return this.alldisabled
      }
    }
  },
  //监控data中的数据变化
  watch: {
    valueId (val) {
      if (val) {
        this.itemObj = this.options.find(item => item.Id == val)
        this.getShareDetailFun(val).catch(err => {
          this.getShareDetailFun(val, 'ID', 1)
        })
      }

    }
  },
  //方法集合
  methods: {
    toPath (stype) {
      this.$router.push('/equityManage/commission')
    },
    async GetCorrListFun () {
      let role = ''
      if (this.alldisabled) {
        //如果是用户
        role = this.RoleId
      } else {
        //如果是身份
        role = this.IdentityId
        if (this.IsSystem == 3 || this.IsSystem == 4) {
          //如果是公司
          return
          role = this.RoleId
        }
      }
      let { Data } = await GetCorrList({ IsPaging: false, Id: role })
      Data.forEach(element => {
        if (element.TacticsName == '分润配置') {
          this.valueId = element.TacticsId
        }
      });
    },
    async getSharefun () {
      let obj = { IsPaging: false }
      // if (this.alldisabled || this.IsSystem == 3 || this.IsSystem == 4) {
      obj.IsSystem = 1
      // }
      let { Data } = await getShare(obj)
      this.options = Data || []

    },
    async getShareDetailFun (val, type = 'ID', systemType) {
      let obj = {
        IsPaging: false,
        Id: val,
        IsSystem: systemType || this.IsSystem
      }
      if (type == 'User') {
        obj.RoleId = val
        delete obj.Id
      } else if (type == 'comp') {
        obj.OrgId = val
        delete obj.Id
      } else if (type == 'team') {
        obj.RoleId = val
        delete obj.Id
      }
      // console.log('去找')
      try {
        let { Data } = await getShareDetail(obj)
        // console.log('找到了吗')
        if (type == 'User' || type == 'comp' || type == 'team') {
          this.options = [Data] || []
          this.valueId = Data.Id
          this.list = Data.Mains || []

          this.hasId = Data.Id
          // console.log('找到了吗')
        } else {
          this.list = Data.Mains || []
        }
      } catch (error) {
        throw ('找不到')
      }

    },
    SaveCorrsFun () {
      if (this.alldisabled) {
        //身份
        let obj =
        {
          "RoleId": this.RoleId, //用户身份角色Id
          "TacticsId": this.valueId, //系统策略Id
          "TacticsName": "分润配置" //对应策略Tab名称
        }
        for (let item in obj) {
          if (!obj[item]) {
            return
          }
        }
        SaveCorrs(obj).then(res => {
          this.$notify({
            title: '保存成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
        })
      } else {
        //用户
        let obj = this.$deepClone(this.itemObj)
        if (this.hasId != obj.Id) {
          obj.Id = '00000000-0000-0000-0000-000000000000'
          let list = this.changeIdtoZero()
          obj.Mains = list
        } else {
          obj.Mains = this.list
        }
        if (this.IsSystem == 3) {
          obj.OrgId = this.RoleId
        } else if (this.IsSystem == 4) {
          obj.RoleId = this.RoleId
        } else {
          //如果是身份   
          // obj.UserId = this.RoleId
          //因为最新版删除用户的策略 UserId后端处理 所以可以不传 但是RoleId变成 角色ID
          obj.RoleId = this.RoleId
        }
        obj.IsSystem = this.IsSystem
        saveShare(obj).then(res => {
          this.resetdataFun()

          this.$notify({
            title: '保存成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
        })
      }
    },
    changeIdtoZero () {
      let list = this.$deepClone(this.list)
      for (let item of list) {
        item.Id = '00000000-0000-0000-0000-000000000000'
        for (let cell of item.Settings) {
          cell.Id = '00000000-0000-0000-0000-000000000000'
          for (let limi of cell.Ratios) {
            limi.Id = '00000000-0000-0000-0000-000000000000'
          }
        }
      }
      return list
    },
    resetdataFun () {
      if (this.alldisabled) {
        //身份那边打开的策略配置
        this.getSharefun().then(_ => {
          // this.GetCorrListFun()
        })
      } else {
        //用户 打开的策略配置
        //this.O_type = type

        this.O_type = 'User'
        if (this.IsSystem == 3 || this.IsSystem == 4) {
          this.IsSystem == 3 && (this.O_type = 'comp')
          this.IsSystem == 4 && (this.O_type = 'team')
          this.getSharefun().then(_ => {
            this.getShareDetailFun(this.RoleId, this.O_type).catch(err => {
              // console.log('第一次打开 没找到可能存在的 已修改的 条目 则在报错的阶段 重新执行另外一条逻辑')
              this.getSharefun().then(_ => {
                // this.GetCorrListFun()
              })
            })
          })
        } else {
          this.getShareDetailFun(this.RoleId, this.O_type).then(res => {
            this.getSharefun()
          }).catch(err => {
            // console.log('第一次打开 没找到可能存在的 已修改的 条目 则在报错的阶段 重新执行另外一条逻辑')
            this.getSharefun().then(_ => {
              // this.GetCorrListFun()
            })
          })
        }

      }
    }

  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {

    this.resetdataFun()


  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {

  },
  beforeCreate () { }, //生命周期 - 创建之前
  beforeMount () { }, //生命周期 - 挂载之前
  beforeUpdate () { }, //生命周期 - 更新之前
  updated () { }, //生命周期 - 更新之后
  beforeDestroy () { }, //生命周期 - 销毁之前
  destroyed () { }, //生命周期 - 销毁完成
  activated () { }, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
//@import url(); 引入公共css类
<style  scoped>
.flex > span:first-child {
  white-space: nowrap;
}
.flex > .el-input {
  width: 80px;
}
.ladder_item {
  width: 85%;
  /* border-bottom: 1px solid #cecece; */
}
.ladder_item + .ladder_item {
  border-top: 2px dashed #f6bcbc;
}
.ladder_name {
  width: 33%;
}
.auto-scroll {
  overflow-y: auto;
  max-height: 300px;
  border-top: 1px solid rgb(240, 240, 240);
}
.commi >>> .el-input-group__append {
  padding: 0 !important;
  text-align: center;
}
.commi >>> .el-input-group--append .el-input__inner {
  padding: 0 !important;
  text-align: center;
}
</style>